package io.geekidea.boot.util.Base;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

public class UrlToBase64Converter {

    /**
     * 从指定URL下载文件并转换为Base64编码
     * @param fileUrl 文件的下载地址
     * @return 文件内容的Base64编码字符串
     * @throws IOException 当网络连接或文件处理发生错误时抛出
     */
    public static String downloadAndConvertToBase64(String fileUrl) throws IOException {
        // 先下载文件内容到字节数组
        byte[] fileContent = downloadFileContent(fileUrl);
        
        // 将字节数组转换为Base64编码
        return Base64.getEncoder().encodeToString(fileContent);
    }
    
    /**
     * 从URL下载文件内容到字节数组
     */
    private static byte[] downloadFileContent(String fileUrl) throws IOException {
        if (fileUrl == null || fileUrl.trim().isEmpty()) {
            throw new IllegalArgumentException("下载地址不能为空");
        }

        URL url = new URL(fileUrl);
        URLConnection connection = null;
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;

        try {
            connection = url.openConnection();
            // 15秒连接超时
            connection.setConnectTimeout(15000);
            // 30秒读取超时
            connection.setReadTimeout(30000);
            
            // 设置请求头，模拟浏览器行为，避免部分服务器拒绝访问
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");

            // 处理HTTP响应
            if (connection instanceof HttpURLConnection) {
                HttpURLConnection httpConn = (HttpURLConnection) connection;
                int responseCode = httpConn.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    throw new IOException("下载失败，HTTP响应码: " + responseCode + 
                                         "，响应消息: " + httpConn.getResponseMessage());
                }
            }

            // 读取文件内容
            inputStream = connection.getInputStream();
            outputStream = new ByteArrayOutputStream();
            // 8KB缓冲区
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();

        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
            if (connection instanceof HttpURLConnection) {
                ((HttpURLConnection) connection).disconnect();
            }
        }
    }
}
